<template>
  <div class="card">
    <div class="card-body">
      <el-button @click="refreshTree()" icon="el-icon-refresh">刷新</el-button>
      <el-tree
        :props="props"
        :load="loadNode"
        v-loading="loading"
        :highlight-current="true"
        lazy
        class="address-tree"
        ref="tree"
      >
        <div class="address-tree-node" slot-scope="{ node, data }">
          <div class="flex">{{ node.label }}</div>
          <el-button
            v-show="!data.edit"
            type="text"
            size="mini"
            @click.stop="e => handleEdit(data)"
          >
            编辑
          </el-button>
        </div>
      </el-tree>
    </div>

    <industrial-edit :visible.sync="editVisible" :form-data="formData"></industrial-edit>
  </div>
</template>

<script>
import IndustrialEdit from './IndustrialEdit'
export default {
  components: { IndustrialEdit },
  props: {},
  data() {
    return {
      props: {
        label: 'ind_class_name',
        isLeaf: 'leaf',
      },
      loading: false,
      tableName: 'industrial_class',
      editVisible: false,
      formData: {},
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    handleEdit(data) {
      this.editVisible = true
      this.formData = { ...data }
    },
    async loadNode(node, resolve) {
      const { data: { ind_class_code = '' } = {} } = node
      const res = await this.getData(ind_class_code)
      resolve(res)
    },

    // 改变顶级数据时，刷新整个tree
    async refreshTree() {
      const { tree } = this.$refs
      if (!tree) return

      try {
        this.loading = true
        const res = await this.getData()
        tree.store.setData(res)
      } catch (error) {
        throw new Error(error)
      } finally {
        this.loading = false
      }
    },
    async getData(code) {
      const params = code
        ? { 'parent_code.eq': code }
        : {
            'orWhere.parent_code.is': 'null',
            'orWhere.parent_code.eq': `''`,
          }
      const res = await this.$api.getData('credit', this.tableName, params)
      const data = res?.data ?? []
      return data.map(it => ({
        ...it,
        edit: false,
        editValue: '',
        loading: false,
        leaf: false,
      }))
    },
  },
}
</script>

<style lang="scss" scoped>
.address-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 0.875rem;
  padding: 1px 4px 1px 0;
}
.address-tag {
  height: 28px;
  line-height: 24px;
  margin: 1px 1px;
}
.address-tree /deep/ .el-tree-node__content {
  height: auto;
}
</style>
